package com.zhenmaitang.clinic_sys.service.impl;

import com.zhenmaitang.clinic_sys.entity.Permission;
import com.zhenmaitang.clinic_sys.entity.Role;
import com.zhenmaitang.clinic_sys.entity.User;
import com.zhenmaitang.clinic_sys.mapper.PermissionMapper;
import com.zhenmaitang.clinic_sys.mapper.RolePermissionMapper;
import com.zhenmaitang.clinic_sys.service.PermissionService;
import com.zhenmaitang.clinic_sys.service.RoleService;
import com.zhenmaitang.clinic_sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserService userService;

    @PostConstruct
    public void init() {
        // 系统启动时检查并初始化默认权限
        initializeDefaultPermissionsIfNeeded();
    }

    private void initializeDefaultPermissionsIfNeeded() {
        // 检查是否已有权限数据，如果没有则初始化
        List<Permission> existingPermissions = permissionMapper.findAll();
        if (existingPermissions.isEmpty()) {
            initializeDefaultPermissions();
        }
    }

    private void initializeDefaultPermissions() {
        // 用户管理权限
        createPermission(new Permission("用户查看", "USER_READ", "USER", "READ", "查看用户信息"));
        createPermission(new Permission("用户创建", "USER_CREATE", "USER", "CREATE", "创建新用户"));
        createPermission(new Permission("用户修改", "USER_UPDATE", "USER", "UPDATE", "修改用户信息"));
        createPermission(new Permission("用户删除", "USER_DELETE", "USER", "DELETE", "删除用户"));
        
        // 部门管理权限
        createPermission(new Permission("部门查看", "DEPARTMENT_READ", "DEPARTMENT", "READ", "查看部门信息"));
        createPermission(new Permission("部门创建", "DEPARTMENT_CREATE", "DEPARTMENT", "CREATE", "创建新部门"));
        createPermission(new Permission("部门修改", "DEPARTMENT_UPDATE", "DEPARTMENT", "UPDATE", "修改部门信息"));
        createPermission(new Permission("部门删除", "DEPARTMENT_DELETE", "DEPARTMENT", "DELETE", "删除部门"));
        
        // 角色管理权限
        createPermission(new Permission("角色查看", "ROLE_READ", "ROLE", "READ", "查看角色信息"));
        createPermission(new Permission("角色创建", "ROLE_CREATE", "ROLE", "CREATE", "创建新角色"));
        createPermission(new Permission("角色修改", "ROLE_UPDATE", "ROLE", "UPDATE", "修改角色信息"));
        createPermission(new Permission("角色删除", "ROLE_DELETE", "ROLE", "DELETE", "删除角色"));
        
        // 财务数据权限
        createPermission(new Permission("财务数据查看", "FINANCE_READ", "FINANCE", "READ", "查看财务相关数据"));
        createPermission(new Permission("财务数据修改", "FINANCE_UPDATE", "FINANCE", "UPDATE", "修改财务相关数据"));
        
        // 人事数据权限
        createPermission(new Permission("人事数据查看", "HR_READ", "HR", "READ", "查看人事相关数据"));
        createPermission(new Permission("人事数据修改", "HR_UPDATE", "HR", "UPDATE", "修改人事相关数据"));
    }

    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.findAll();
    }

    @Override
    public Permission getPermissionById(Integer id) {
        return permissionMapper.findById(id);
    }

    @Override
    public Permission getPermissionByCode(String code) {
        return permissionMapper.findByCode(code);
    }

    @Override
    public Permission createPermission(Permission permission) {
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        permissionMapper.insert(permission);
        return permission;
    }

    @Override
    public Permission updatePermission(Permission permission) {
        permission.setUpdateTime(LocalDateTime.now());
        permissionMapper.update(permission);
        return permission;
    }

    @Override
    public void deletePermission(Integer id) {
        permissionMapper.deleteById(id);
    }

    @Override
    public Set<String> getPermissionsByRoleName(String roleName) {
        Role role = roleService.getRoleByName(roleName);
        if (role == null) {
            return new HashSet<>();
        }
        
        // 从数据库查询角色的权限
        List<Permission> permissions = permissionMapper.findPermissionsByRoleId(role.getId());
        return permissions.stream()
                .map(Permission::getCode)
                .collect(Collectors.toSet());
    }

    @Override
    public boolean hasPermission(String username, String permissionCode) {
        // 获取用户角色
        com.zhenmaitang.clinic_sys.entity.User user = userService.findByUsername(username);
        if (user == null || user.getRole() == null || user.getRole().isEmpty()) {
            return false;
        }
        
        // 检查用户的所有角色是否有指定权限
        for (String role : user.getRole()) {
            Set<String> rolePermissions = getPermissionsByRoleName(role);
            if (rolePermissions.contains(permissionCode)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean hasResourcePermission(String username, String resource, String action) {
        // 构建权限代码
        String permissionCode = resource.toUpperCase() + "_" + action.toUpperCase();
        return hasPermission(username, permissionCode);
    }
    
    @Override
    public List<Permission> getPermissionsByRoleId(Integer roleId) {
        return permissionMapper.findPermissionsByRoleId(roleId);
    }
    
    @Override
    public void assignPermissionsToRole(Integer roleId, List<Integer> permissionIds) {
        // 先清空角色的所有权限
        rolePermissionMapper.clearRolePermissions(roleId);
        
        // 然后分配新的权限
        if (permissionIds != null && !permissionIds.isEmpty()) {
            rolePermissionMapper.batchAssignPermissionsToRole(roleId, permissionIds);
        }
    }
    
    @Override
    public Set<String> getAllResources() {
        List<Permission> permissions = permissionMapper.findAll();
        return permissions.stream()
                .map(Permission::getResource)
                .collect(Collectors.toSet());
    }
    
    @Override
    public Set<String> getAllActions() {
        List<Permission> permissions = permissionMapper.findAll();
        return permissions.stream()
                .map(Permission::getAction)
                .collect(Collectors.toSet());
    }

    @Override
    public List<String> getPermissionsByUserId(Integer userId) {
        // 获取用户信息
        User user = userService.findById(userId);
        if (user == null || user.getRole() == null || user.getRole().isEmpty()) {
            return new ArrayList<>();
        }
        
        // 合并用户所有角色的权限
        Set<String> allPermissions = new HashSet<>();
        for (String role : user.getRole()) {
            allPermissions.addAll(getPermissionsByRoleName(role));
        }
        
        return new ArrayList<>(allPermissions);
    }
}